package com.cy.store.service.impl;

import com.cy.store.entity.Address;
import com.cy.store.entity.Order;
import com.cy.store.entity.OrderItem;
import com.cy.store.mapper.OrderMapper;
import com.cy.store.service.IAddressService;
import com.cy.store.service.ICartService;
import com.cy.store.service.IOrderService;
import com.cy.store.service.ex.InsertException;
import com.cy.store.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author: AngJie
 * @create: 2022-02-11 13:11
 **/
@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    IAddressService addressService;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    ICartService cartService;

    @Override
    public Order create(Integer aid, Integer uid, String username, List<Integer> cids) {
        List<CartVo> list = cartService.getVoByCid(cids, uid);
        //计算商品的总价格
        Long total = 0L;
        for (CartVo c :
                list) {
            total += c.getRealPrice() * c.getNum();
        }
        Address address = addressService.getByAid(aid, uid);
        Order order = new Order();
        order.setUid(uid);
        //收货地址数据
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        order.setRecvProvince(address.getProvinceCode());
        order.setRecvCity(address.getCityName());
        order.setRecvArea(address.getAreaName());
        order.setRecvAddress(address.getAddress());
        //支付、总价、时间
        order.setStatus(0);
        order.setTotalPrice(total);
        //日志
        Date date = new Date();
        order.setCreatedUser(username);
        order.setCreatedTime(date);
        order.setModifiedUser(username);
        order.setModifiedTime(date);

        Integer rows = orderMapper.insertOrder(order);
        if (rows != 1) {
            throw new InsertException("插入时发生了未知异常");
        }

        //创建订单详细项
        for (CartVo c :
                list) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOid(order.getOid());
            orderItem.setPid(c.getPid());
            orderItem.setTitle(c.getTitle());
            orderItem.setImage(c.getImage());
            orderItem.setPrice(c.getRealPrice());
            orderItem.setCreatedUser(username);
            orderItem.setCreatedTime(date);
            orderItem.setModifiedUser(username);
            orderItem.setModifiedTime(date);

            rows = orderMapper.insertOrderItem(orderItem);
            if (rows != 1) {
                throw new InsertException("插入数据时发生未知的异常");
            }
        }
        return order;
    }
}
